package com.powernode.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.BusinessEnum;
import com.powernode.constant.HttpConstants;
import com.powernode.model.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName AccessDeniedHandlerImpl
 * @Description 认证拒绝处理器--处理携带token, 但权限不足的请求
 * @Date 2024/07/21 15:07
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    /**
     * 当用户没有权限访问某个资源时，会调用这个方法
     * @param request 请求
     * @param response 响应
     * @param accessDeniedException 认证拒绝异常
     * @throws IOException io异常
     * @throws ServletException servlet异常
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 设置响应头
        response.setContentType(HttpConstants.APPLICATION_JSON);
        request.setCharacterEncoding(HttpConstants.UTF_8);
        // 结果返回
        Result<Object> failResult = Result.fail(BusinessEnum.ACCESS_DENY_FAIL);
        String responseStr = new ObjectMapper().writeValueAsString(failResult);
        PrintWriter writer = response.getWriter();
        writer.write(responseStr);
        writer.flush();
        writer.close();
    }
}
